package com.gardenguell.salad.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.gardenguell.salad.R;
import com.gardenguell.salad.app.AppConstant;
import com.gardenguell.salad.app.HandlerCenter;
import com.gardenguell.salad.helper.SimpleWifiHelper;
import com.gardenguell.salad.task.ConfigWifiTask;
import com.gardenguell.salad.ui.activity.base.ToolbarActivity;
import com.gardenguell.salad.ui.view.MaterialDialog;
import com.gardenguell.salad.util.AsyncTaskUtil;
import com.gardenguell.salad.task.ConfigWifiTask.Command;
import com.gardenguell.salad.util.ResUtil;
import com.gardenguell.salad.util.SharedPreferenceUtil;
import com.gardenguell.salad.util.WifiUtil;

/**
 * Created by absurd on 2015/11/20.
 */
public class ConfigActivity extends ToolbarActivity {

    public static final int CONFIG_WIFI = 0;
    public static final int ADD_BOX = 1;

    private static final String LOG_LABLE = "config module wifi --> ";

    private TextView mSSIDTv;
    private TextView mPasswordTv;
    private String mSSID;
    private String mPassword;

    private int mType;

    private SimpleWifiHelper mHelper = new SimpleWifiHelper();


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_configure_module;
    }

    @Override
    public boolean canBack() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(getIntent() != null) {
            mType = getIntent().getFlags();
        }

        setToolbarTitle("");
        findViewById(R.id.btn_configure_wifi).setClickable(false);
        mSSIDTv = (TextView)findViewById(R.id.tv_first);
        mPasswordTv = (TextView)findViewById(R.id.tv_second);


    }

    @Override
    protected void onStart() {
        super.onStart();
        // find the module in current wifi
        AsyncTaskUtil.addTaskInPool(new ConfigWifiTask( mHelper, ResUtil.getString(R.string.tip_seek_the_module)){

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                super.onPostExecute(aBoolean);
                if(aBoolean) {
                    log.i(LOG_LABLE + "find a module in current wifi enviroment, module ip " + mHelper.getModuleIp());
                    // get the mac of the module connected currently
                    AsyncTaskUtil.addTaskInPool(new ConfigWifiTask(mHelper,ResUtil.getString(R.string.tip_get_module_mac)){
                        @Override
                        protected void onPostExecute(Boolean aBoolean) {
                            super.onPostExecute(aBoolean);
                            if(aBoolean){
                                prefUtil.put(AppConstant.PREF_TOKEN.MODULE_MAC, mHelper.getModuleMac());
                                log.i(LOG_LABLE + "get module mac successfully, module mac --> " + mHelper.getModuleMac());
                                // set the server ip and port for the module
                                AsyncTaskUtil.addTaskInPool(new ConfigWifiTask(mHelper, ResUtil.getString(R.string.tip_set_server_info)){
                                    @Override
                                    protected void onPostExecute(Boolean aBoolean) {
                                        super.onPostExecute(aBoolean);
                                        if(aBoolean){
                                            log.i(LOG_LABLE + "config the server infos of the module successfully");
                                            // get the name of the module
                                            AsyncTaskUtil.addTaskInPool(new ConfigWifiTask( mHelper, ResUtil.getString(R.string.tip_get_module_name)){
                                                @Override
                                                protected void onPostExecute(Boolean aBoolean) {
                                                    super.onPostExecute(aBoolean);
                                                    if(aBoolean){
                                                        if(!ConfigActivity.this.isFinishing()) {
                                                            final MaterialDialog alert = new MaterialDialog(ConfigActivity.this);
                                                            alert.setMessage(ResUtil.getString(R.string.conect_module) + " " + mHelper.getModuleName())
                                                                    .setPositiveButton(R.string.ok, new View.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(View v) {
                                                                            alert.dismiss();
                                                                        }
                                                                    }).show();
                                                             // get the module info and config the server infos successfully
                                                            findViewById(R.id.btn_configure_wifi).setClickable(true);
                                                        }
                                                    }else{
                                                        log.i(LOG_LABLE + "failed to get the name of the module connected successfully");
                                                        Toast.makeText(ConfigActivity.this, R.string.get_module_name_failed, Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            },Command.NAME);
                                        }else{
                                            log.i(LOG_LABLE + "failed to config the server infos of the module");
                                        }
                                    }
                                }, Command.CONFIG_SERVER_INFO);
                            }else{
                                log.i(LOG_LABLE + "failed to get the mac of the module connected currently");
                            }
                        }
                    }, Command.MAC);
                }else{
                    if(!ConfigActivity.this.isFinishing()) {
                        final MaterialDialog alert = new MaterialDialog(ConfigActivity.this);
                        alert.setMessage(R.string.no_module_in_wifi)
                                .setPositiveButton(R.string.setting, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        alert.dismiss();
                                        Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                        startActivity(intent);
                                    }
                                }).show();
                    }
                }
            }
        }, Command.FIND);
    }

    public void onClick(View view){
        switch(view.getId()){
            case R.id.btn_direct_in:
                finish();
                break;
            case R.id.btn_configure_wifi:
                mSSID = mSSIDTv.getText().toString().trim();
                mPassword = mPasswordTv.getText().toString().trim();
                log.i("ssid --> " + mSSID + " , password --> " + mPassword);
                final ConfigWifiTask configTask = new ConfigWifiTask(mHelper, ResUtil.getString(R.string.tip_config_the_module)){
                    @Override
                    protected void onPostExecute(Boolean aBoolean) {
                        super.onPostExecute(aBoolean);
                        if(aBoolean){
                            AsyncTaskUtil.addTaskInPool(new ConfigWifiTask(mHelper, ResUtil.getString(R.string.tip_reconnect_router)){
                                @Override
                                protected void onPostExecute(Boolean aBoolean) {
                                    super.onPostExecute(aBoolean);
                                    if(aBoolean){
                                        if(WifiUtil.getInstance().isWifiContected(mSSID)){
                                            Toast.makeText(ConfigActivity.this, R.string.config_module_success, Toast.LENGTH_SHORT).show();
                                            if(mType == CONFIG_WIFI){
                                                HandlerCenter.getInstance().getHandler(HandlerCenter.Flag.MAIN_ACTIVITY)
                                                        .sendEmptyMessage(HandlerCenter.Message.CONFIG_WIFI);
                                            }else if(mType == ADD_BOX){
                                                Message msg = Message.obtain();
                                                msg.obj = mHelper.getModuleMac();
                                                msg.what = HandlerCenter.Message.ADD_NEW_BOX;
                                                HandlerCenter.getInstance().getHandler(HandlerCenter.Flag.MAIN_ACTIVITY)
                                                        .sendMessage(msg);
                                            }
                                            ConfigActivity.this.finish();
                                        }else{
                                            Toast.makeText(ConfigActivity.this, mSSID + ResUtil.getString(R.string.ssid_pass_error), Toast.LENGTH_SHORT).show();
                                        }
                                    }else{
                                        // Toast.makeText(ConfigActivity.this, mSSID + ResUtil.getString(R.string.ssid_pass_error), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }, Command.CONNECT, mSSID, mPassword);

                        }else{
                            log.i(LOG_LABLE + "failed to config the ssid and password of the router to the module");
                            Toast.makeText(ConfigActivity.this, R.string.config_module_failed, Toast.LENGTH_SHORT).show();
                        }
                    }
                };
                AsyncTaskUtil.addTaskInPool(configTask, Command.CONFIG, mSSID, mPassword);
                /**
                AsyncTaskUtil.addTaskInPool(new ConfigWifiTask( mHelper, ResUtil.getString(R.string.tip_test_ssid_password)){
                    @Override
                    protected void onPostExecute(Boolean aBoolean) {
                        super.onPostExecute(aBoolean);
                        boolean res = WifiUtil.getInstance().isWifiContected(mSSID);
                        if(res){
                            log.i(LOG_LABLE + "the ssid and passowrd are correct");
                            AsyncTaskUtil.addTaskInPool(new ConfigWifiTask( mHelper, ResUtil.getString(R.string.tip_reconnect_module)){
                                @Override
                                protected void onPostExecute(Boolean aBoolean) {
                                    super.onPostExecute(aBoolean);
                                    boolean res = WifiUtil.getInstance().isWifiContected(mHelper.getModuleName());
                                    if(res) {
                                        AsyncTaskUtil.addTaskInPool(configTask, Command.CONFIG, mSSID, mPassword);
                                    }else{
                                        Toast.makeText(ConfigActivity.this, mHelper.getModuleName() + ResUtil.getString(R.string.ssid_pass_error), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }, Command.CONNECT, mHelper.getModuleName(), "");
                        }else{
                            log.i(LOG_LABLE + "the ssid and passowrd are not correct");
                            Toast.makeText(ConfigActivity.this, R.string.ssid_pass_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                }, Command.CONNECT, mSSID, mPassword);
                 **/
                break;
            default:
                break;
        }
    }



}
